using DA.AnimGraph;
using OdinSerializer;
using System.Collections.Generic;
using System.Linq;

namespace DA.AnimGraph.Editor {
    internal class AGANode_LayerBlend : AGANode_BlendBase, IResourceNode {
        public override AGANodeModelBase modelProperty { set => model = (AGANodeModel_LayerBlend)value; get => model; }
        [OdinSerialize] AGANodeModel_LayerBlend model;

        public AGANode_LayerBlend(AGANodeModelBase model) : base(model) {
            inputChildren.Add(AUIDGenerator.Gen());
            inputNames.Add("layer 0");
            inputChildren.Add(AUIDGenerator.Gen());
            inputNames.Add("layer 1");
            inputChildren.Add(AUIDGenerator.Gen());
            inputNames.Add("layer 2");
            this.model.layerDescs.Add(new AGAFieldModel_Layer());
            this.model.layerDescs.Add(new AGAFieldModel_Layer());
        }

        public override int Publish(List<PublishNode> outNodes, AGAPublisher.PublishContext context) {
            var pNode = new LayerBlendPNode();
            pNode.uuid = uuid;
            pNode.data = model.Publish(context);
            var index = outNodes.Count;
            outNodes.Add(pNode);

            pNode.inputChildren = new int[inputChildren.Count];
            for (int i = 0; i < inputChildren.Count; i++) {
                var childUuid = inputChildren[i];
                var childNode = context.subGraph.FindNextNodeInstance(uuid, childUuid) as AGANode_FunctionBase;
                if (childNode != null) pNode.inputChildren[i] = AGAPublisher.ExportNode(childNode, outNodes, context);
                else pNode.inputChildren[i] = -1;
            }

            PublishPerks(pNode, context);
            return index;
        }

        public AUID[] GetResources() {
            return model.GetResources();
        }
        public void ReplaceResourceAUID(Dictionary<AUID, AUID> uuidMapping) {
            model.ReplaceResourceAUID(uuidMapping);
        }
    }


    [ModelOf(typeof(AGANode_LayerBlend))]
    internal class AGANodeModel_LayerBlend : AGANodeModelBase {

        public List<AGAFieldModel_Layer> layerDescs = new();

        internal LayerBlendNode.SetupData Publish(AGAPublisher.PublishContext context) {

            return new LayerBlendNode.SetupData() {
                layerDescs = layerDescs.Select(x => x.Publish(context)).ToArray()
            };
        }
        public AUID[] GetResources() {
            return layerDescs.Select(x => x.mask.maskKey).Where(x => x.isValid).ToArray();
        }
        public void ReplaceResourceAUID(Dictionary<AUID, AUID> uuidMapping) {
            foreach (var p in layerDescs) {
                if (uuidMapping.TryGetValue(p.mask.maskKey, out var newId)) {
                    p.mask.maskKey = newId;
                }
            }
        }
    }
}
